/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;


import Datos.Personal;
import Negocio.Negocio;
import javax.swing.JOptionPane;

/**
 *
 * @author Mufase
 */
public class RegistroPersonal extends javax.swing.JDialog {

    /**
     * Creates new form RegistroPersonal
     */
    public RegistroPersonal(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbOcupacion = new javax.swing.JComboBox();
        btnIngresar = new javax.swing.JButton();
        btnConsultar = new javax.swing.JButton();
        btnVolver = new javax.swing.JButton();
        txtNombre = new javax.swing.JTextField();
        txtRut = new javax.swing.JTextField();
        btnEliminar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registro de Personal");
        setResizable(false);

        jLabel1.setText("Nombre:");

        jLabel2.setText("Rut:");

        jLabel3.setText("Ocupacion:");

        cmbOcupacion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione...", "Conductor", "Auxiliar" }));

        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        btnVolver.setText("Volver");
        btnVolver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVolverActionPerformed(evt);
            }
        });

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        txtRut.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtRutKeyTyped(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnIngresar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnConsultar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnVolver))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbOcupacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtRut, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                                .addComponent(btnEliminar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtRut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbOcupacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnIngresar)
                    .addComponent(btnConsultar)
                    .addComponent(btnVolver))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
         // Validar el ingreso de datos
        if (this.txtRut.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Debe Ingresar Rut", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.txtRut.requestFocus();
            return;
        }
        if(this.validarRut() == false)
        {
            JOptionPane.showMessageDialog(this, "Rut incorrecto",
                    "Error de Ingreso",JOptionPane.ERROR_MESSAGE);
            this.txtRut.requestFocus();
            return;
        }        
        if (this.txtNombre.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Debe Ingresar Nombre", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.txtNombre.requestFocus();
            return;
        }
        if (this.cmbOcupacion.getSelectedItem()=="Seleccione...") {
            JOptionPane.showMessageDialog(this, "Debe seleccionar ocupacion", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.cmbOcupacion.requestFocus();
            return;
        }
        
        Personal per = new Personal();
        Negocio neg = new Negocio();
     
        if(this.cmbOcupacion.getSelectedIndex()== 1){
               
               per.setRut(this.txtRut.getText().trim());
               per.setNombre(this.txtNombre.getText().trim());
               per.setOcupacion("Conductor");
               neg.ingresarConductor(per);
        }else{
            if(this.cmbOcupacion.getSelectedIndex()==2){
                
                per.setRut(this.txtRut.getText().trim());
                per.setNombre(this.txtNombre.getText().trim());
                per.setOcupacion("Auxiliar");
                neg.ingresarAuxiliar(per);
            }
        }
        
         JOptionPane.showMessageDialog(this, "Personal ha sido registrado", "Informacion", JOptionPane.INFORMATION_MESSAGE);
            this.txtRut.requestFocus();
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void btnVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVolverActionPerformed
      int opcion = 0;
        opcion = JOptionPane.showConfirmDialog(this, "¿Desea volver al Menu Principal?", "Salir de Registro de Personal",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION) {
            this.dispose();
        }
    }//GEN-LAST:event_btnVolverActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
       Negocio neg=new Negocio();
       
       Personal per=neg.buscarPersonal(this.txtRut.getText().trim());
        
        if(per.getRut().trim().length()!=0){
            this.txtNombre.setText(per.getNombre());
            this.cmbOcupacion.setSelectedItem(per.getOcupacion());
        }
        else
        {
        JOptionPane.showMessageDialog(this,"Rut no existe","Error de Ingreso", JOptionPane.ERROR_MESSAGE);
        this.txtRut.requestFocus();
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        int opcion = 0;

        opcion = JOptionPane.showConfirmDialog(this, "¿Desea eliminar Personal?", "confirmar eliminacion",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION) {
            Negocio neg = new Negocio();
            neg.eliminarPersonal(this.txtRut.getText().trim());

            this.txtRut.setText("");
            this.txtNombre.setText("");
            this.cmbOcupacion.setSelectedIndex(0);
            this.txtRut.requestFocus();

            JOptionPane.showMessageDialog(this, "Personal eliminado", "Informacion", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtRutKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRutKeyTyped
        if (this.txtRut.getText().trim().length() > 9) {
            evt.consume();
        }
    }//GEN-LAST:event_txtRutKeyTyped

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
       
        if (evt.getKeyChar() > '0' && evt.getKeyChar() < '9') {
            evt.consume();
        } else {
            if (this.txtNombre.getText().trim().length() > 40) {
                evt.consume();
            }
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RegistroPersonal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RegistroPersonal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RegistroPersonal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RegistroPersonal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                RegistroPersonal dialog = new RegistroPersonal(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JButton btnVolver;
    private javax.swing.JComboBox cmbOcupacion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtRut;
    // End of variables declaration//GEN-END:variables

    private boolean validarRut()
    {
        boolean valido = true;
        int suma = 0;
        int pond = 2;
        int resto = 0;
        int valor = 0;
        String digito = "";
        int largo = this.txtRut.getText().trim().length()-2;
        int ultimo = this.txtRut.getText().trim().length()-1;
        
        for(int i=largo-1; i>-1; i--)
        {
            //System.out.println(this.txtRut.getText().trim().charAt(i));
            suma = suma + 
                    (Integer.parseInt(""+this.txtRut.getText().trim().charAt(i))
                    * pond);
            pond++;
            if(pond > 7)
            {
                pond = 2;
            }
        }
        //System.out.println("suma: " + suma);
        resto = suma % 11;
        valor = 11 - resto;
        if(valor == 10)
        {
            digito = "K";          
        }
        else
        {
            if (valor == 11)
            {
                digito = "0";
            }
            else
            {
                digito = "" + valor;
            }
        }
        
        if(this.txtRut.getText().trim().charAt(ultimo) != digito.trim().charAt(0))
        {
            valido = false;
        }        
        return valido;
    }



}
